<?php
/**
 * Created by PhpStorm.
 * User: LG
 * Date: 2017/8/31
 * Time: 14:43
 */

namespace app\admin\controller;

use app\common\model\Operation;
use app\common\model\WorkOrder;
use app\common\model\Customer;
use think\Cache;
use think\Db;

class Operationmanagement extends Base
{
    protected $Operation;
    protected $workOrder;
    protected $Customer;
    public function __construct()
    {
        parent::__construct();

        $this->Operation = new Operation();

        $this->workOrder = new WorkOrder();

        $this->Customer = new Customer();
    }

    /**
     * 运营中心列表
     * @author  ligang
     * @request     string      title       GET     角色名称
     * @request     int         page        GET     页码
     */
    public function index(){

        //获取条件
        $request = input('');
        $where =array();
        //去除空格
        foreach ($request as $tk=>$tv){
            $request[$tk] = trim($tv);
        }
        foreach ($request as $k=>$v){
            if ($k == 'page'){
                continue;
            }
            if (empty($v)){
                continue;
            }
            if ($k == 'datetimeStart'){
                $where[$k] = $v;
                continue;
            }
            if ($k == 'datetimeEnd'){
                $where[$k] = $v;
                continue;
            }
            $where[$k] = ['like','%'.$v.'%'];
        }
        //获取页码
        $Nowpage = input('get.page') ? input('get.page'):1;
        //获取数据
        $lists = $this->Operation->selectPage($Nowpage,$where);
        //模板输出
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $lists['page']['allpage']); //总页数
        $this->assign('count', $lists['page']['count']);
        //更改时间格式
        foreach ($lists['data'] as $key=>$value){
            $lists['data'][$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
            $lists['data'][$key]['Administrative_number'] = $this->Operation->getAdministrative(['operation'=>$value['o_id']]);
        }
        $json = array();
        $json['data'] = $lists['data'];
        $json['page'] =  $lists['page'];
        $operation = $this->Operation->selectOperationInfo();
        $administrative = $this->Operation->selectAdministrativeInfo();
        $this->assign('operation',$operation);
        $this->assign('administrative',$administrative);
        if(input('get.page')){
            return json($json);
        }
        //渲染模板
        return $this->fetch('operation/operation_management');
    }

    /*
     *  修改运营中心---回显
     * @author  ligang
     * @request     int         id        GET     页码
     */
    public function editOperation(){

        $id = input('get.id/d');
        $data = $this->Operation->findOperation(array('o_id'=>$id));
        $checkAccount = $this->Operation->bindAccount(3,['o_id'=>$id,'is_admin'=>1]);
        if($checkAccount){
            $this->assign('admin',$checkAccount);
        }
        $this->assign('data',$data);

        $address = $this->Operation->selectOperationInfo();
        $province_id = '';
        foreach ($address as $key => $value){
            if ($value['province_id'] == $data['province_id']){
                continue;
            }
            $province_id .= $value['province_id'].',';
        }
        $province_id = substr($province_id,0,-1);
        $where['id'] = ['not in',$province_id];

        //模板赋值
        $Province = $this->Operation->areasProvince($where);
        $this->assign('Province',$Province);
        //渲染模板
        return $this->fetch('operation/add_operation_center');
    }
    /*
     *  添加运营中心---回显
     * @author  ligang
     * @request     int         id        GET     页码
     */
    public function AddOperation(){

        $address = $this->Operation->selectOperationInfo();
        $province_id = '';
        foreach ($address as $key => $value){
            $province_id .= $value['province_id'].',';
        }
        $province_id = substr($province_id,0,-1);
        $where['id'] = ['not in',$province_id];
        //模板赋值
        $Province = $this->Operation->areasProvince($where);
        $this->assign('Province',$Province);
        //渲染模板
        return $this->fetch('operation/add_operation_center');
    }
    /*
     *  添加（修改）运营中心
     * @author  ligang
     * @request     int         o_id        GET     运营中心ID(修改)
     */
    public function doEditOperation(){
        $data= $this->request->post();
        //去除空格
        foreach ($data as $tk=>$tv){
            $data[$tk] = trim($tv);
        }

        //分组
        $admin = [];
        $operation = [];
        $msg = '';
        foreach ($data as $key => $value){
            if (empty($value)){
                $msg = $key;
            }
            if (strpos($key,'min_') != false){
                $admin[substr($key,6)] = $value;
                unset($data[$key]);
            }else{
                $operation[$key] = $value;
            }
        }
        //检验是否为空
        switch ($msg){
            case 'admin_account':
                $msg = '账号';
                break;
            case 'admin_email':
                $msg = '邮箱';
                break;
            case 'company_name':
                $msg = '运营中心名称';
                break;
            case 'province_id':
                $msg = '省';
                break;
            case 'address':
                $msg = '详细地址';
                break;
            case 'name':
                $msg = '联系人';
                break;
            case 'phone':
                $msg = '电话';
                break;
            default:
                $msg = '';
        }
        if (!empty($msg)){
            return ['code'=>0,'msg'=>$msg."不能为空"];
        }
        $admin['address'] = $operation['address'];
        $admin['name'] = $operation['name'];
        $admin['phone'] = $operation['phone'];
        //图片上传
        $file = request()->file('avatar_img');
        $is_upload = false;
        if(empty($file)){
            $is_upload = true;
        }else{
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $admin['avatar_img'] = $info->getSaveName();
            }
        }
        //验证
        if (strlen($admin['phone']) != 11){
            $json['code'] = 0;
            $json['msg'] = "绑定账号：手机格式不正确";
            return json($json);
        }
        if (strlen($admin['phone']) != 11){
            $json['code'] = 0;
            $json['msg'] = "运营中心：手机格式不正确";
            return json($json);
        }
        if (!inge_isemail($admin['email'])){
            $json['code'] = 0;
            $json['msg'] = "绑定账号：邮箱格式不正确";
            return json($json);
        }
        if (strlen($admin['password']) <= 5 && !empty($admin['password'])){
            $json['code'] = 0;
            $json['msg'] = "绑定账号：密码最少六位";
            return json($json);
        }
        //新增、修改操作
        if (!empty($operation['o_id'])){
            /**
             * 修改运营中心 + 绑定账号
             */
            if(!empty($admin['password'])){
                $password = setPassword($admin['password']);
                $admin['password'] = $password['password'];
                $admin['strict'] = $password['strict'];
            }else{
                unset($admin['password']);
            }
            $operation['update_time'] = time();
            //更新操作
            Db::startTrans();
            try{
                $this->Operation->updateOperation($operation);
                $this->Operation->updateOperationAccount(['o_id'=>$operation['o_id'],'is_admin'=>1],$admin);
                Db::commit();
                return json(array('code'=>1,'msg'=>'修改成功'));
            }catch (\Exception $e){
                Db::rollback();
                return json(array('code'=>0,'msg'=>'修改失败'));
            }

        }else{
            /**
             * 新增运营中心 + 绑定账号
             */
            if ($is_upload){
                return json(['code'=>0,'msg'=>'请上传头像']);
            }
            $checkOperation = $this->Operation->findOperation(['company_name'=>$operation['company_name']]);
            if ($checkOperation){
                $json['code'] = 0;
                $json['msg'] = "运营中心名称已存在";
            }
            //检查绑定账号是否唯一
            $checkAccount = $this->Operation->bindAccount(3,['account'=>$admin['account']]);
            if ($checkAccount){
                return  ['code'=>0,'msg'=>"账号已存在"];
            }
            if(empty($admin['password'])){
                $admin['password'] = 123456;
            }
            $password = setPassword($admin['password']);
            $admin['password'] = $password['password'];
            $admin['strict'] = $password['strict'];
            $admin['is_admin'] = 1;
            $admin['status'] = 1;
            $admin['add_time'] = time();
            $operation['add_time'] = time();
            unset($operation['o_id']);
            //更新操作
            Db::startTrans();
            try{
                $result = $this->Operation->insertOperation($operation);
                $admin['o_id'] = $result;
                $this->Operation->bindAccount(1,[],$admin);
                Db::commit();
                return ['code'=>1,'msg'=>"新增成功"];
            }catch (\Exception $e){
                echo $e;
                Db::rollback();
                return ['code'=>0,'msg'=>"新增失败"];
            }

        }
    }

    /**
     * 运营中心详情
     * @author  ligang
     * @request     int         id        GET     运营中心ID
     */
    public function details()
    {
        $where = array();
        //检验get参数
        if (input('?get.id')){
            //获取参数并强制转换为int型
            $where['rq_operation_info.o_id'] = input('get.id/d');
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        //获取数据
        $data = $this->Operation->selectPage(1,$where);

        $map['operation_id'] = $where['rq_operation_info.o_id'];
        $data['data'][0]['add_time'] = date('Y-m-d H:i:s',$data['data'][0]['add_time']);
        $data['data'][0]['Administrative_number'] = $this->Operation->getAdministrative(['operation'=>$where['rq_operation_info.o_id']]);
        //未完成工单数
        $map['work_order_status'] = [['>',1],['<',11],'and'];
        $data['data'][0]['no_complete'] = $this->workOrder->getCount($map,'rq_work_order');
        //上月已完成工单数
        $map['work_order_status'] = 11;
        $data['data'][0]['last_month'] = $this->workOrder->getCount($map,'rq_work_order','','','update_time','last month');
        //本月新增用户数
        $data['data'][0]['month_user'] = $this->Customer->CountUserNumber(['operation_id'=>$where['rq_operation_info.o_id']],['add_time'=>'month']);

        $this->assign('data',$data['data'][0]);
        //渲染模板
        return $this->fetch("/operation/operation_center_details");
    }

    /**
     * 运营中心模块删除
     * 删除时，当前运营中心下面不能有下一级
     * @author  ligang
     * @request     array         id        GET     ID
     * @request     string        type      GET     模块
     */
    public function delete()
    {
        //定义返回格式
        $json = array('code'=>1,'msg'=>'提示信息');
        $data = input('');
        if (!empty($data['type']) && !empty($data['data'])){
            $type = $data['type'];
            $id = $data['data'];
            //判断板块
            switch ($type){
                //运营中心
                case "box":
                    foreach ($id as $key => $value){
                        //判断是否存在当前运营中心的账号
                        //$checkAccount = $this->Operation->bindAccount(3,['o_id'=>$value,'is_delete'=>0]);
                        //判断是否存在当前运营中心的行政区域
                        $checkSubordinate = $this->Operation->findAdministrative(['operation'=>$value,'is_delete'=>0]);
                        //if($checkSubordinate || $checkAccount){
                        if($checkSubordinate){
                            $json['code'] = 0;
                            $json['msg'] = "请删除所属运营中心下级单位";
                            return   json($json);
                            break;
                        }
                        $result = $this->Operation->deleteData('operation_info','o_id',$value,'运营中心');
                        if (!$result) {
                            $json['code'] = 0;
                            $json['msg'] = "删除失败";
                            break;
                        }else{
                            $json['code'] = 1;
                            $json['msg'] = "删除成功";
                        }
                    }
                    return  json($json);
                    break;
                //行政区域
                case "box2":
                    foreach ($id as $key => $value){
                        //判断是否存在当前行政区域的账号
                        $checkAccount = $this->Operation->bindAccount(4,['a_id'=>$value,'is_delete'=>0]);
                        //判断是否存在当前行政区域的工程人员
                        $checkEngineers = $this->Operation->findEngineers(['administrative_id'=>$value,'is_delete'=>0]);
                        if($checkEngineers || $checkAccount){
                            $json['code'] = 0;
                            $json['msg'] = "请删除所属行政区域账号和工程人员";
                            return   json($json);
                            break;
                        }
                        $result = $this->Operation->deleteData('administrative_info','a_id',$value,'行政区域');
                        if (!$result) {
                            $json['code'] = 0;
                            $json['msg'] = "删除失败";
                            break;
                        }else{
                            $json['code'] = 1;
                            $json['msg'] = "删除成功";
                        }
                    }
                    return  json($json);
                    break;
                //工程人员
                case "box3":
                    foreach ($id as $key => $value){
                        Db::startTrans();
                        try {
                            $this->Operation->deleteData('engineers', 'engineers_id', $value, '工程人员');
                            $engineers_number = $this->Operation->findEngineers(['engineers_id' => $value])['engineers_number'];
                            Db::name('personnel_number')->where(['personnel_number' => $engineers_number])->delete();
                            Db::commit();
                            $json['code'] = 1;
                            $json['msg'] = "删除成功";
                        }catch (\Exception $e){
                            $json['code'] = 0;
                            $json['msg'] = "删除失败";
                            // 回滚事务
                            Db::rollback();
                            break;
                        }
                    }
                    return  json($json);
                    break;
                default:
                    $json['code'] = 0;
                    $json['msg'] = "非法请求";
                    return json($json);
                    break;
            }
        }else{
            $json['code'] = 0;
            $json['msg'] = "缺少必要参数";
            return json($json);
        }
    }

    /*
     *  行政区域
     */

    public function profile()
    {
        //获取条件
        $request = input('');
        $where =array();
        //去除空格
        foreach ($request as $tk=>$tv){
            $request[$tk] = trim($tv);
        }
        foreach ($request as $k=>$v){

            if ($k == 'page'){
                continue;
            }
            if (empty($v) && strlen($v) == 0){
                continue;
            }
            if ($k == 'name'){
                $where['rq_administrative_info.'.$k] = ['like','%'.$v.'%'];
                continue;
            }
            if ($k == 'phone'){
                $where['rq_administrative_info.'.$k] = $v;
                continue;
            }
            if ($k == 'company_name'){
                $where['rq_administrative_info.'.$k] = ['like','%'.$v.'%'];
                continue;
            }
            $where[$k] = $v;
        }
//        dump($where);
//        exit();
        //获取页码
        $Nowpage = input('get.page') ? input('get.page'):1;
        //获取数据
        $lists = $this->Operation->selectDataProfile($Nowpage,$where);
        foreach ($lists['data'] as $key => $value){
            if ($value['status'] == 1){
                $lists['data'][$key]['status'] = "正常";
            }else{
                $lists['data'][$key]['status'] = "冻结";
            }
            $lists['data'][$key]['add_time'] = get_time($value['add_time']);
        }
        //模板输出
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $lists['page']['allpage']); //总页数
        $this->assign('count', $lists['page']['count']);
        $json = array();


        $json['data'] = $lists['data'];
        $json['page'] =  $lists['page'];

        if(input('get.page')){
            return json($json);
        }

    }

    /**
     * 行政区域详情
     * @author  ligang
     * @request     int         id        GET     运营中心ID
     */
    public function profileDetails()
    {
        $where = array();
        //检验get参数
        if (input('?get.id')){
            //获取参数并强制转换为int型
            $where['rq_administrative_info.a_id'] = input('get.id/d');
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        //获取数据
        $data = $this->Operation->selectDataProfile(1,$where);
//        dump($data);
        $data['data'][0]['add_time'] = date('Y-m-d H:i:s',$data['data'][0]['add_time']);
        $this->assign('data',$data['data'][0]);
        //渲染模板
        return $this->fetch("/operation/administrative_division_details");
    }


    /*
     *  添加（修改）行政区域---回显
     * @author  ligang
     * @request     int         o_id        GET     行政区域ID(修改)
     */
    public function editProfile()
    {
        //模板赋值
        if (input('?get.id')) {
            $id = input('get.id/d');
            $data = $this->Operation->findAdministrative(array('a_id' => $id));
            $area = array();
            if (strpos($data['area_name'], ',') != false) {
                $arr_area_name = explode(',', $data['area_name']);
                $arr_area_id = explode(',', $data['area_id']);
                foreach ($arr_area_name as $k => $v) {
                    $area[$k]['area_name'] = $v;
                    $area[$k]['area_id'] = $arr_area_id[$k];
                }
                $data['area'] = $area;
            }
//            dump($data);
            $this->assign('data', $data);
        }
        $Province = $this->Operation->areasProvince();
        $City = $this->Operation->areasCity();
        $Area = $this->Operation->areaName();
        $operation = $this->Operation->selectOperationInfo();
        $administrative = $this->Operation->selectAdministrativeInfo();
        $this->assign('Province',$Province);
        $this->assign('City',$City);
        $this->assign('Area',$Area);
        $this->assign('operation',$operation);
        $this->assign('administrative',$administrative);

        //渲染模板
        return $this->fetch('operation/add_administrative_division');
    }


    /*
     *  添加（修改）行政区域
     * @author  ligang
     * @request     int         o_id        GET     行政区域ID(修改)
     */
    public function doEditProfile()
    {
        //定义返回格式
        $json = array('code'=>1,'msg'=>"提示信息");
        //检验数据
        $data = input('');
        $field = "";
        foreach ($data as $k=>$v){
            if ($k == "area_id" || $k == "area_name"){
                continue;
            }
            //去掉首位空格
            $data[$k] = trim($v);
        }
        foreach ($data as $key => $value){
            if ($key == "area_id" || $key == "area_name"){
                foreach ($data['area_id'] as $ka => $va){
                    if (!empty($va)){
                        $field = $key;
                        break;
                    }
                }
            }
            if (empty($value) && $key != "a_id" && $key != "status"){
                $field = $key;
                break;
            }

        }
        //匹配字段名称
        switch ($field){
            case "company_name":
                $msg = "行政区域名称";
                break;
            case "operation":
                $msg = "所属运营中心";
                break;
            case "address":
                $msg = "详细地址";
                break;
            case "name":
                $msg = "联系人";
                break;
            case "phone":
                $msg = "联系电话";
                break;
            case "province_id":
                $msg = "省";
                break;
            case "province_name":
                $msg = "省";
                break;
            case "city_id":
                $msg = "市";
                break;
            case "city_name":
                $msg = "市";
                break;
            case "area_id":
                $msg = "区/县";
                break;
            case "area_name":
                $msg = "区/县";
                break;
            default:
                $msg = "";
        }

        if (!empty($msg)){
            $json['code'] = 0;
            $json['msg'] = $msg."不能为空";
            return json($json);
        }
        if (!inge_ismobile($data['phone'])){
            $json['code'] = 0;
            $json['msg'] = "手机格式不正确";
            return json($json);
        }
        if (is_array($data['area_id']) && is_array($data['area_name'])){
            $data['area_id'] = implode(',',$data['area_id']);
            $data['area_name'] = implode(',',$data['area_name']);
        }
        if (input('?get.a_id') && !empty(input('get.a_id'))){
            /*
             * 修改
             */
            $data['a_id'] = intval(input('get.a_id'));
            //修改状态
            if ($data['status'] == 0){
                $FrozenAccount = $this->Operation->bindAccount(5,['a_id'=>$data['a_id']],['status'=>0]);
                if ($FrozenAccount){
                    //日志
                    writelog(session('admin_useruid'),session('admin_userusername'),'用户【'.session('admin_userusername').'】冻结成功：行政区域',1,'admin_log');
                }else{
                    //日志
                    writelog(session('admin_useruid'),session('admin_userusername'),'用户【'.session('admin_userusername').'】冻结失败：行政区域',0,'admin_log');
                }
            }else{
                $FrozenAccount = $this->Operation->bindAccount(5,['a_id'=>$data['a_id']],['status'=>1]);
                if ($FrozenAccount){
                    //日志
                    writelog(session('admin_useruid'),session('admin_userusername'),'用户【'.session('admin_userusername').'】修改成功：行政区域',1,'admin_log');
                }else{
                    //日志
                    writelog(session('admin_useruid'),session('admin_userusername'),'用户【'.session('admin_userusername').'】修改成功：行政区域',0,'admin_log');
                }
            }
            $data['update_time'] = time();
            $res = $this->Operation->updateAdministrativen($data);
            if ($res == 0){
                return json(array('code'=>0,'msg'=>'修改失败'));
            }else{
                return json(array('code'=>1,'msg'=>'修改成功'));
            }
        }else{
            //添加
            $data['add_time'] = time();
            $checkAdministrativen = $this->Operation->findAdministrative(array('company_name'=>$data['company_name']));
            if ($checkAdministrativen){
                return json(array('code'=>0,'msg'=>'该行政区域已经存在'));
            }
            $res = $this->Operation->insertAdministrativen($data);
            if ($res == 0){
                return json(array('code'=>0,'msg'=>'添加失败'));
            }else{
                return json(array('code'=>1,'msg'=>'添加成功'));
            }
        }

    }

    /*
     *工程部人员管理
     * @author  ligang
     */
    public function personnel()
    {
        //获取条件
        $request = input('');
        $where =array();
        //去除空格
        foreach ($request as $tk=>$tv){
            $request[$tk] = trim($tv);
        }
        foreach ($request as $k=>$v){
            if ($k == 'page'){
                continue;
            }
            if (empty($v)){
                continue;
            }
            if ($k == 'o_id'){
                $where['rq_operation_info.'.$k] = $v;
                continue;
            }
            if ($k == 'engineers_name'){
                $where[$k] = ['like','"%'.$v.'%"'];
                continue;
            }
            if($k == 'administrative_id'){
                $where['rq_engineers.'.$k] = $v;
                continue;
            }
            $where[$k] = $v;
        }
        //获取页码
        $Nowpage = input('get.page') ? input('get.page'):1;
        //获取数据
        $lists = $this->Operation->selectPageEngineers($Nowpage,$where);
        foreach ($lists['data'] as $key => $value){
            if ($value['engineers_status'] == 1){
                $status = "冻结";
            }else{
                $status = "正常";
            }
            $lists['data'][$key]['engineers_status'] = $status;
        }
        //模板输出
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $lists['page']['allpage']); //总页数
        $this->assign('count', $lists['page']['count']);
        $json = array();
        $json['data'] = $lists['data'];
        $json['page'] =  $lists['page'];

        if(input('get.page')){
            return json($json);
        }

    }

    /**
     * 工程部人员管理详情
     * @author  ligang
     * @request     int         id        GET     运营中心ID
     */
    public function personnelDetails()
    {
        $where = array();
        //检验get参数
        if (input('?get.id')){
            //获取参数并强制转换为int型
            $where['rq_engineers.engineers_id'] = input('get.id/d');
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        //获取数据
        $data = $this->Operation->selectPageEngineers(1,$where);
        $data['data'][0]['reg_time'] = date('Y-m-d H:i:s',$data['data'][0]['reg_time']);
//        dump($data['data'][0]);
        $this->assign('data',$data['data'][0]);
        //渲染模板
        return $this->fetch("/operation/engineering_administration_details");
    }

    /*
     *  添加（修改）工程部人员管理---回显
     * @author  ligang
     * @request     int         id        GET     工程部人员管理(修改)
     */
    public function editPersonnel()
    {
        //模板赋值
        if (input('?get.id')) {
            $id = input('get.id/d');
            $data = $this->Operation->selectPageEngineers(1,array('rq_engineers.engineers_id' => $id));
            $this->assign('data', $data['data'][0]);
        }
        $Province = $this->Operation->areasProvince();
        $City = $this->Operation->areasCity();
        $Area = $this->Operation->areaName();
        $this->assign('Province',$Province);
        $this->assign('City',$City);
        $this->assign('Area',$Area);
        $operation = $this->Operation->selectOperationInfo();
        $administrative = $this->Operation->selectAdministrativeInfo();
        $this->assign('operation',$operation);
        $this->assign('administrative',$administrative);
        //渲染模板
        return $this->fetch('operation/add_engineeringpersonnel');
    }

    /*
     *  工程人员编辑
     * @author  ligang
     * @request     int         id        GET     工程部人员管理(修改)
     */
    public function doEditPersonnel()
    {


        //定义返回格式
        $json = array('code'=>1,'msg'=>'提示信息');
        //检验提交数据
        $data = $this->request->post();

        $field = '';
        foreach ($data as $k=>$v){
            //去掉首位空格
            $data[$k] = trim($v);
        }
        foreach ($data as $key => $value){
            //新增时需要默认登录密码
            if (empty($data['engineers_id']) && $key == "engineers_password" && empty($value)){
                $data['engineers_password'] = 123456;
                break;
            }
            if (empty($value) && $key != "engineers_id" && $key != "engineers_password"){
                $field = $key;
                break;
            }
        }
        //匹配字段名称
        switch ($field){
            case "operation":
                $msg = "所属运营中心";
                break;
            case "administrative":
                $msg = "所属行政区域";
                break;
            case "engineers_name":
                $msg = "工程人员名称";
                break;
            case "engineers_password":
                $msg = "登录密码";
                break;
            case "engineers_phone":
                $msg = "工程人员电话";
                break;
            case "engineers_idcard":
                $msg = "身份证号码";
                break;
            case "engineers_address":
                $msg = "家庭住址";
                break;
            case "engineers_status":
                $msg = "账号状态";
                break;
            default:
                $msg = "";
        }
        if (!empty($msg)){
            $json['code'] = 0;
            $json['msg'] = $msg."不能为空";
            return json($json);
        }
        if (!inge_ismobile($data['engineers_phone'])){
            $json['code'] = 0;
            $json['msg'] = "手机格式不正确";
            return json($json);
        }
        if (!checkIdCard($data['engineers_idcard'])){
            $json['code'] = 0;
            $json['msg'] = "身份证格式不正确";
            return json($json);
        }
        $data['birthday'] = getBirthday($data['engineers_idcard']);
        if (!empty($data['engineers_id'])){
            //修改
            if(!empty($_FILES['avatar_img']['name'])){
                $file = request()->file('avatar_img');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    $data['avatar_img'] = $info->getSaveName();
                }else{
                    return json(['code'=>0,'msg'=>$file->getError()]);
                }
            }
            if (empty($data['engineers_password'])){
                unset($data['engineers_password']);
            }else{
                $password = setPassword(trim($data['engineers_password']));
                $data['engineers_password'] = $password['password'];
                $data['engineers_slat'] = $password['strict'];
            }
            $res = $this->Operation->updateEngineers($data);
            if ($res == 0){
                return json(array('code'=>0,'msg'=>'修改失败'));
            }else{
                return json(array('code'=>1,'msg'=>'修改成功'));
            }
        }else{
            //添加
            //图片上传
            $file = request()->file('avatar_img');
            if(empty($file)){
                return json(['code'=>0,'msg'=>'请上传用户头像']);
            }

            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $data['avatar_img'] = $info->getSaveName();
            }else{
                return json(['code'=>0,'msg'=>$file->getError()]);
            }
            $password = setPassword(trim($data['engineers_password']));
            $data['engineers_number'] = EmployeeNumber();
            $data['engineers_password'] = $password['password'];
            $data['department'] = 0;//？
            $data['engineers_slat'] = $password['strict'];
            $data['reg_time'] = time();
            $checkEngineers = $this->Operation->findEngineers(['engineers_number'=>$data['engineers_number'],'engineers_phone'=>$data['engineers_phone']]);
            if ($checkEngineers){
                return json(array('code'=>0,'msg'=>'该工程人员已经存在'));
            }
            $res = $this->Operation->insertEngineers($data);
            if ($res == 0){
                return json(array('code'=>0,'msg'=>'添加失败'));
            }else{
                return json(array('code'=>1,'msg'=>'添加成功'));
            }
        }

    }

    /*
     * 运营中心绑定账号
     * @author  ligang
     * @Explain 绑定账号后不可编辑，可以查看
     */
    public function bindAccountOperation()
    {
        //获取参数
        $data = request()->post();
        //是否绑定，若绑定则返回绑定的信息
//        $checkAccount = $this->Operation->bindAccount(3,['o_id'=>$data['o_id'],'is_admin'=>1]);
//        if($checkAccount){
//            return ['code'=>1,'data'=>$checkAccount];
//        }

        //图片上传
        $file = request()->file('avatar_img');
        if(empty($file)){
            return json(['code'=>0,'msg'=>'请上传用户头像']);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $data['avatar_img'] = $info->getSaveName();
        }
        $field = '';
        //去掉首位空格
        foreach ($data as $k=>$v){
            $data[$k] = trim($v);
        }
        //检验参数是否为空
        foreach ($data as $key => $value){
            //若密码不存在，则设置默认密码
            if ($key == "password" && empty($value)){
                $data[$key] = 123456;
                continue;
            }
            if (empty($value)){
                $field = $key;
                break;
            }
        }
        switch ($field){
            case "account":
                $msg = "帐号";
                break;
            case "email":
                $msg = "邮箱地址";
                break;
            case "admin_name":
                $msg = "联系人姓名";
                break;
            case "admin_phone":
                $msg = "联系电话";
                break;
            case "address":
                $msg = "地址";
                break;
            default:
                $msg = "";
        }
        if (!empty($msg)){
            return ['code'=>0,'msg'=>$msg."不能为空"];
        }
        //检查绑定账号是否唯一
        $checkAccount = $this->Operation->bindAccount(3,['account'=>$data['account']]);
        if ($checkAccount){
            return  ['code'=>0,'msg'=>"账号已存在"];
        }
        $password = setPassword($data['password']);
        $data['password'] = $password['password'];
        $data['strict'] = $password['strict'];
        $data['is_admin'] = 1;
        $data['status'] = 1;
        $data['add_time'] = time();
        $bindAccount = $this->Operation->bindAccount(1,[],$data);
        if ($bindAccount){
            return ['code'=>1,'msg'=>"绑定成功"];
        }else{
            return ['code'=>0,'msg'=>"绑定失败"];
        }

    }

    /*
     *  行政区域绑定账号
     *  @author ligang
     *  @Explain 绑定账号后不可编辑，可以查看
     */
    public function bindAccountAdministrative()
    {
        //获取参数
        $data = request()->post();
        //判断是否绑定，若绑定则返回绑定信息
        $checkAccount = $this->Operation->bindAccount(4,['a_id'=>$data['a_id'],'is_admin'=>1]);
        if($checkAccount){
            return json(['code'=>1,'data'=>$checkAccount]);
        }

        //图片上传
        $file = request()->file('avatar_img');
        if(empty($file)){
            return json(['code'=>0,'msg'=>'请上传用户头像']);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $data['avatar_img'] = $info->getSaveName();
        }
        $field = '';
        //去掉首位空格
        foreach ($data as $k=>$v){
            $data[$k] = trim($v);
        }
        //检查参数是否为空
        foreach ($data as $key => $value){
            //设置默认密码
            if ($key == "password" && empty($value)){
                $data[$key] = 123456;
                continue;
            }
            if (empty($value)){
                $field = $key;
                break;
            }
        }
        switch ($field){
            case "account":
                $msg = "帐号";
                break;
            case "email":
                $msg = "邮箱地址";
                break;
            case "admin_name":
                $msg = "联系人姓名";
                break;
            case "admin_phone":
                $msg = "联系电话";
                break;
            case "address":
                $msg = "地址";
                break;
            default:
                $msg = "";
        }
        if (!empty($msg)){
            return json(['code'=>0,'msg'=>$msg."不能为空"]);
        }
        //检查绑定账号是否唯一
        $checkAccount = $this->Operation->bindAccount(4,['account'=>$data['account']]);
        if ($checkAccount){
            return  json(['code'=>0,'msg'=>"账号已存在"]);
        }
        $password = setPassword($data['password']);
        $data['password'] = $password['password'];
        $data['strict'] = $password['strict'];
        $data['is_admin'] = 1;
        $data['status'] = 1;
        $data['add_time'] = time();
        $bindAccount = $this->Operation->bindAccount(2,$data);
        if ($bindAccount){
            return json(['code'=>1,'msg'=>"绑定成功"]);
        }else{
            return json(['code'=>0,'msg'=>"绑定失败"]);
        }

    }

    /**
     * 根据运营中心获取行政中心
     * @author ligang
     * @Request operation_id             int    GET   运营中心ID
     * @return array
     */
    public function selectAdministrative()
    {
        $where = array();
        if(input('?get.operation') && !empty(input('get.operation'))){
            $where['operation'] = input('get.operation/d');
        }else{
            $where = "1=1";
        }
        $administrative = $this->Operation->selectAdministrativeInfo($where);
        return $administrative;
    }

    /**
     * 根据省获取市
     * @author ligang
     * @Request province             int    GET   省ID
     * @return array|bool
     */
    public function selectCity()
    {
        $province_id = '';
        if(input('?get.province') && !empty(input('get.province'))) {
            $province_id = input('get.province');
        }
        $City = $this->Operation->areasCity($province_id);
        return json($City);
    }

    /**
     * 根据市获取区县
     * @author ligang
     * @Request province             int    GET   省ID
     * @return array
     */
    public function selectArea()
    {
        $City_id = '';
        if(input('?get.city') && !empty(input('get.city'))) {
            $City_id = input('get.city/d');
        }else{
            return array();
        }
        $City = $this->Operation->areaName($City_id);
        return json($City);
    }


}